#! /bin/bash
ifzookeeepr1=`grep "ZOOKEEPER" /etc/profile`
ifzookeeepr2=`grep "zookeeper" /etc/profile`
zoo1=$(echo ${ifzookeeepr1} | grep "ZOOKEEPER")
zoo2=$(echo ${ifzookeeepr2} | grep "zookeeper")
if [[ "$zoo1" != "" || "$zoo2" != "" ]]
then
    echo "zookeeper was installed"
else
	echo "--------------begin install zookeeper--------------"
	basepath="/usr/local"
	installpath=$(cd `dirname $0`; pwd)
	zookeepername="apache-zookeeper-3.5.8"
	# install zookeeper
	wget http://mirror.bit.edu.cn/apache/zookeeper/stable/${zookeepername}-bin.tar.gz
	tar -zxvf ${zookeepername}-bin.tar.gz -C ${basepath}
	cd ${basepath}/${zookeepername}/conf
	cp zoo_sample.cfg zoo.cfg
	cd ..
	mkdir dataDir
	mkdir dataLogDir
	cd conf
	sed -i "s!dataDir=/tmp/zookeeper!dataDir=${basepath}/${zookeepername}/dataDir\ndataLogDir=${basepath}${zookeepername}/dataLogDir!g" zoo.cfg
	# config zookeeper
	echo "export ZOOKEEPER_HOME=${basepath}/${zookeepername}" >> /etc/profile
	echo "PATH=$PATH:$ZOOKEEPER_HOME/bin" >> /etc/profile
	source /etc/profile
	# set zookeeper-service auto start when reboot
	touch /etc/systemd/system/zookeeper.service
	echo "[Unit]
	Description=zookeeper
	After=network.target remote-fs.target nss-lookup.target
	[Service]
	Type=forking
	ExecStart=${basepath}/zookeeper-test-3.5.8/bin/zkServer.sh start
	ExecReload=${basepath}/zookeeper-test-3.5.8/bin/zkServer.sh restart
	ExecStop=${basepath}/zookeeper-test-3.5.8/bin/zkServer.sh stop
	[Install]
	WantedBy=multi-user.target" >> /etc/systemd/system/zookeeper.service
	systemctl daemon-reload
	chmod 777 /etc/systemd/system/zookeeper.service
	systemctl enable zookeeper.service
	echo "--------------install success!------------"
	echo "if zookeeper environment invalid please execute command: source /etc/profile"
fi